$(function () {
    var accountCache = {}, platformBalance = 0;

    /**
     * 加载平台资金账户信息
     */
    var queryAccounts = function () {
        var accountDiv = $("#accountDiv");
        $.get("fund/queryPlatformAccounts", function (map) {
            var accounts = map.accounts, config = map.config, names = {};

            names[config.accounts.primaryAccount.id] = config.accounts.primaryAccount.name;
            names[config.accounts.reserveAccount.id] = config.accounts.reserveAccount.name;
            names[config.accounts.feeAccount.id] = config.accounts.feeAccount.name;

            if (accounts && accounts.length > 0) {
                var cls = accounts.length === 4 ? 'col-md-4' : 'col-md-3';
                accountDiv.html("");
                for (var i = 0; i < accounts.length; i++) {
                    var account = accounts[i], id = account.subAcctId;
                    account.cls = cls;
                    account.name = names[id];

                    if (id !== 'BASEDT') {
                        var acct = sys.render("#accountTemplate", account);
                        accountDiv.append($(acct));
                        $(".account-select").append($("<option></option>").attr("value", id).text(names[id]));
                        if (id === 'MDT000001') {
                            $(".platform-balance").text(account.avlBal);
                            platformBalance = parseFloat(account.avlBal);
                        }
                        accountCache[id] = account;
                    }
                }
            } else {
                accountDiv.html("无子账号信息");
            }
        });
    };

    var initEvents = function () {
        /**
         * 用户快捷取现
         */
        var userDirectWithdrawBtn = $("#userDirectWithdrawBtn"),
            userDirectWithdrawBalanceBtn = $("#userDirectWithdrawBalanceBtn"),
            userDirectWithdrawBalance = $("#userDirectWithdrawForm .user-balance");

        userDirectWithdrawBalanceBtn.on("click", function () {
            var user = $("#userDirectWithdrawForm input[name=user]").val();
            if (user === '') {
                alert("请输入用户登录名或手机号");
                return;
            }
            userDirectWithdrawBalanceBtn.html($('<i class="fa fa-spin fa-spinner"></i>')).prop("disabled", true);
            userDirectWithdrawBalance.html($('<i class="fa fa-spin fa-spinner"></i>'));
            $.get("user/queryUser/" + user, function (u) {
                if (u) {
                    if (u.id === null || u.id === '') {
                        alert("用户不存在");
                        return;
                    }
                    // 查询余额
                    $.get("pnr/queryUserBalance/" + u.id, function (res) {
                        if (res !== undefined && res.availableBalance !== null) {
                            userDirectWithdrawBalance.text($.number(res.availableBalance, 2));
                        } else {
                            userDirectWithdrawBalance.text("0.00");
                            alert("用户尚未开通三方支付");
                        }
                        userDirectWithdrawBalanceBtn.html("查询余额").prop("disabled", false);
                    });
                } else {
                    userDirectWithdrawBalance.text("0.00");
                    userDirectWithdrawBalanceBtn.html("查询余额").prop("disabled", false);
                    alert("用户不存在");
                }
            });
        });
        userDirectWithdrawBtn.on("click", function () {
            var user = $("#userDirectWithdrawForm input[name=user]").val();
            $.get("user/queryUser/" + user, function (u) {
                if (u) {
                    if (u.id === null || u.id === '') {
                        alert("取现用户不存在");
                        return;
                    }
                    $("#userDirectWithdrawForm input[name=userId]").val(u.id);
                    var amount = $("#userDirectWithdrawForm input[name=amount]").val();
                    userDirectWithdrawBtn.prepend($('<i class="fa fa-spin fa-spinner mr5"></i>')).prop("disabled", true);
                    // 异步请求
                    $.post("pnr/userDirectWithdraw", {
                        userId: u.id,
                        amount: amount
                    }, function (res) {
                        if (res === true) {
                            alert("用户快捷取现成功");
                            location.reload();
                        } else {
                            alert("用户快捷取现失败");
                        }
                        userDirectWithdrawBtn.html("取现").prop("disabled", false);
                    });
                } else {
                    alert("取现用户不存在");
                }
            });
        });

        /**
         * 平台向用户转账
         */
        var userTransferBtn = $("#userTransferBtn"), userTransAmount = $("#userTransferForm input[name=amount]");
        userTransferBtn.on("click", function () {
            var user = $("#userTransferForm input[name=user]").val(), btn = $(this);
            sys.btnSpin(btn);
            $.get("user/queryUser/" + user, function (u) {
                if (u) {
                    if (u.id === null || u.id === '') {
                        sys.alert("转入用户不存在");
                        sys.btnStop(btn);
                        return;
                    }
                    if (userTransAmount.val() === '') {
                        sys.alert("转账金额不可为空");
                        sys.btnStop(btn);
                        return;
                    }
                    if (isNaN(userTransAmount.val())) {
                        sys.alert("转账金额格式错误");
                        sys.btnStop(btn);
                        return;
                    }
                    //sys.processModal();
                    $("#userTransferForm input[name=userId]").val(u.id);
                    //$("#userTransferForm").submit();
                    var data = $("#userTransferForm").formToJson();
                    $.post("fund/userTransfer", data, function (res) {
                        if (res.success) {
                            sys.alert("转账申请提交成功，请耐心等待审核", function () {
                                location.reload();
                            });
                            sys.btnStop(btn);
                        } else {
                            sys.alert("转账申请提交失败");
                            sys.btnStop(btn);
                        }
                    });

                } else {
                    sys.alert("转入用户不存在");
                    sys.btnStop(btn);
                }
            });
        });
        /**
         * 平台普通取现
         */
        var platformWithdrawBtn = $("#platformWithdrawBtn");

        platformWithdrawBtn.on("click", function () {
            var amount = $("#platformWithdrawForm input[name=amount]").val();
            if (amount === '') {
                sys.alert("请输入取现金额");
                return;
            }
            if (isNaN(amount)) {
                sys.alert("取现金额格式不正确");
                return;
            }
            if (amount > platformBalance) {
                sys.alert("取现金额超过平台余额");
                return;
            }
            $("#platformWithdrawForm").submit();
        });
        /**
         * 平台快捷取现
         */
        var platformDirectWithdrawBtn = $("#platformDirectWithdrawBtn");

        platformDirectWithdrawBtn.on("click", function () {
            var amount = $("#platformDirectWithdrawForm input[name=amount]").val();
            platformDirectWithdrawBtn.prepend($('<i class="fa fa-spin fa-spinner mr5"></i>')).prop("disabled", true);
            $.post("pnr/platformDirectWithdraw", {
                amount: amount
            }, function (res) {
                if (res === true) {
                    alert("平台快捷取现成功");
                    location.reload();
                } else {
                    alert("平台快捷取现失败");
                }
                platformDirectWithdrawBtn.html("取现").prop("disabled", false);
            });
        });

        /**
         * 平台子账户之间转账
         */
        var transferBtn = $("#transferBtn"),
            transferForm = $("#transferForm"),
            transferAmountInput = $("#transferForm input[name=amount]");

        transferBtn.on("click", function () {
            var inAccount = $("#transferForm select[name=inAccount]").val(),
                outAccount = $("#transferForm select[name=outAccount]").val();

            if (inAccount === outAccount) {
                sys.alert("转入转出账号不可一样");
                return;
            }

            var amount = parseFloat($("#transferForm input[name=amount]").val()),
                outBalance = accountCache[outAccount].avlBal;

            if (amount > outBalance) {
                sys.alert("转账金额超出转出账户余额");
                return;
            }

            if (isNaN(amount)) {
                sys.alert("转账金额格式不正确");
                return;
            }

//            sys.confirm("#modalConfirm", function () {
//                alert("hehe");
//            });
            // 触发转账

            sys.btnSpin(transferBtn);
            //transferForm.submit();

            $.post("pnr/transfer", {
                outAccount: outAccount,
                inAccount: inAccount,
                amount: amount
            }, function (res) {
                if (res === true) {
                    sys.alert("转账成功", function () {
                        location.reload();
                    });
                } else {
                    sys.alert("转账失败");
                }
            }).fail(function () {
                sys.alert("网络通信异常");
            });
        });

    };

    var initPage = function () {
        queryAccounts();
        initEvents();
    };

    // 初始化页面
    initPage();
});